package com.south.base.test.arithmetic.dynamic.programming;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author Administrator
 * @date 2019/12/2 10:07
 */
public class Sum {
    /**
     * 给定一个整数数组 nums ，找到一个具有最大和的连续子数组（子数组最少包含一个元素），返回其最大和。
     */
    @Test
    public void maxSubArray() {
        Assert.assertEquals(6, maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
        Assert.assertEquals(6, maxSubArray2(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
    }

    public int maxSubArray(int[] nums) {
        int[] dp = new int[nums.length];
        int sum = dp[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (dp[i - 1] > 0) {
                dp[i] = dp[i - 1] + nums[i];
            } else {
                dp[i] = nums[i];
            }
            sum = Math.max(sum, dp[i]);
        }
        return sum;
    }

    public int maxSubArray2(int[] nums) {
//        int[] dp = new int[nums.length];
        int maxSum = nums[0];
        int lastSum = maxSum;
        int currentSum;
        for (int i = 1; i < nums.length; i++) {
            if (lastSum > 0) {
                currentSum = lastSum + nums[i];
            } else {
                currentSum = nums[i];
            }
            maxSum = Math.max(maxSum, currentSum);
            lastSum = currentSum;
        }
        return maxSum;
    }
}
